package com.whfc.openapi.api.car.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultUtil;
import com.whfc.common.third.szyc.car.Cmd1Req;
import com.whfc.common.third.szyc.car.Cmd1Res;
import com.whfc.common.third.szyc.car.CmdConst;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.ImageUtil;
import com.whfc.common.util.JSONUtil;
import com.whfc.fuum.dto.open.OpenApiClientDTO;
import com.whfc.openapi.api.car.service.OpenCarDataService;
import com.whfc.openapi.constant.OpenApiConst;
import com.whfc.uni.dto.CarInoutRecordSyncDTO;
import com.whfc.uni.enums.Direction;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;

/**
 * 车辆识别记录同步
 *
 * @author : qzexing
 * @version : 1.0
 * @date : 2020/6/20 11:32
 */
@RestController
@RequestMapping("/open/api/v1/car")
public class CarDataController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OpenCarDataService openCarDataService;


    /**
     * 车辆识别记录(通用接口)
     *
     * @param clientDTO
     * @param deviceName
     * @param name
     * @param licensePlate
     * @param time
     * @param direction
     * @param img
     * @return
     * @throws Exception
     */
    @RequestMapping("/record")
    public Result record(@RequestAttribute(OpenApiConst.OPENAPI_CLIENT) OpenApiClientDTO clientDTO,
                         @RequestParam("deviceName") String deviceName,
                         @RequestParam("name") String name,
                         @RequestParam("licensePlate") String licensePlate,
                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam("time") Date time,
                         @RequestParam("direction") Integer direction,
                         @RequestParam(value = "img", required = false) MultipartFile img) throws Exception {
        logger.info("车辆识别记录同步,client:{},deviceName:{},name:{},licensePlate:{},time:{},direction:{}", clientDTO.getAppKey(), deviceName, name, licensePlate, time, direction);
        openCarDataService.recordSync(clientDTO.getDeptId(), deviceName, name, licensePlate, time, direction, img.getInputStream());
        return ResultUtil.success();
    }

    /**
     * 车辆识别(雄安项目)
     *
     * @param clientDTO
     * @param jsonStr
     * @param files
     * @return
     */
    @RequestMapping("/record/sync")
    public Result recordSync(@RequestAttribute(OpenApiConst.OPENAPI_CLIENT) OpenApiClientDTO clientDTO,
                             @RequestParam("jsonStr") String jsonStr,
                             @RequestParam(value = "files", required = false) MultipartFile[] files) {
        logger.info("车辆识别记录同步,client:{},CarInOutRecordSyncDTO:{}", clientDTO, jsonStr);
        CarInoutRecordSyncDTO recordSyncDTO = JSON.parseObject(jsonStr, CarInoutRecordSyncDTO.class);
        recordSyncDTO.setDeptId(clientDTO.getDeptId());
        openCarDataService.insertRecord(recordSyncDTO, files);
        return ResultUtil.success();
    }

    /**
     * 车辆识别(深圳玉川)
     *
     * @param clientDTO
     * @param msg
     * @return
     */
    @RequestMapping("/record/szyc")
    public Object recordSzyc(@RequestAttribute(OpenApiConst.OPENAPI_CLIENT) OpenApiClientDTO clientDTO,
                             @RequestParam("Msg") String msg) {
        logger.debug("车辆识别记录同步,client:{},msg:{}", clientDTO, msg);
        Integer deptId = clientDTO.getDeptId();
        try {
            JSONObject reqMsg = JSON.parseObject(msg);
            if (reqMsg != null) {
                String cmd = reqMsg.getString(CmdConst.CMD_FIELD);
                switch (cmd) {
                    case CmdConst.CMD_1:
                        Cmd1Req req = JSONUtil.parseObject(msg, Cmd1Req.class);
                        this.processCmd1(deptId, req);
                        Cmd1Res res = new Cmd1Res(CmdConst.SUCCESS, "", req.getRecordid());
                        return JSONUtil.toString(res);
                    default:
                        break;
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
        }
        return "";
    }

    /**
     * 车辆识别推送(华夏相机)
     *
     * @param clientDTO
     * @param plateNum
     * @param startTime
     * @param parkId
     * @param vdcType
     * @param picture
     * @return
     */
    @PostMapping(value = "/record/sx")
    public String hxRecordSync(@RequestAttribute(OpenApiConst.OPENAPI_CLIENT) OpenApiClientDTO clientDTO,
                               @RequestParam("plate_num") String plateNum,
                               @RequestParam("start_time") Long startTime,
                               @RequestParam("park_id") String parkId,
                               @RequestParam("vdc_type") String vdcType,
                               @RequestParam("picture") String picture) {
        Integer deptId = clientDTO.getDeptId();
        logger.info("华夏相机车辆识别记录同步,deptId:{},param:{},{},{},{},{}", deptId, plateNum, startTime, parkId, vdcType, StringUtils.length(picture));
        Direction direction = Direction.parseEname(vdcType);
        Date time = new Date(startTime * 1000);
        openCarDataService.recordSync(clientDTO.getDeptId(), parkId, "-", plateNum, time, direction.getValue(), picture);
        return "{\"error_num\":0,\"error_str\":\"\"}";
    }

    /**
     * 车辆识别推送(芊熠相机)
     *
     * @param clientDTO
     * @param body
     * @return
     */
    @PostMapping("/record/oeuvre")
    public String recordOeuvre(@RequestAttribute(OpenApiConst.OPENAPI_CLIENT) OpenApiClientDTO clientDTO,
                               @RequestBody String body) {
        logger.info("芊熠相机识别推送,deptId:{},body:{}", clientDTO.getDeptId(), body);

        try {
            JSONObject data = JSONObject.parseObject(body);
            if (data != null && data.containsKey("AlarmInfoPlate")) {
                JSONObject alarmInfoPlate = data.getJSONObject("AlarmInfoPlate");
                JSONObject result = alarmInfoPlate.getJSONObject("result");
                JSONObject plateResult = result.getJSONObject("PlateResult");
                String deviceName = alarmInfoPlate.getString("deviceName");
                String license = plateResult.getString("license");
                Direction direction = Direction.IN.getValue().equals(plateResult.getInteger("direction")) ? Direction.IN : Direction.OUT;
                String imageFile = plateResult.getString("imageFile");
                Long timeStamp = plateResult.getJSONObject("timeStamp").getJSONObject("Timeval").getLong("sec");
                Date time = new Date(timeStamp * 1000);
                openCarDataService.recordSync(clientDTO.getDeptId(), deviceName, "-", license, time, direction.getValue(), imageFile);
            }
        } catch (Exception ex) {
            logger.error("", ex);
        }
        return "{\"Response_AlarmInfoPlate\":{\"info\":\"ok\",\"content\":\"retransfer_stop\",\"is_pay\":\"true\"，\"serialData\":[]}}";
    }


    /**
     * 处理指令1(车辆进出记录)
     *
     * @param deptId
     * @param req
     */
    private void processCmd1(Integer deptId, Cmd1Req req) {
        logger.info("处理车辆进出记录,deptId:{},req:{}", deptId, JSONUtil.toString(req));
        //进
        if (CmdConst.IN.equals(req.getDirection())) {
            String name = req.getUsername();
            String licensePlate = req.getVLP();
            String deviceName = req.getInchannelname();
            Date time = DateUtil.parseDate(req.getIntime(), "yyyy-MM-dd HH:mm:ss");
            Integer direction = Direction.IN.getValue();
            String img = req.getInpicturedata();
            //base64图片解码
            InputStream inputStream = null;
            if (StringUtils.isNotBlank(img) && img.length() > 1024) {
                byte[] imageBytes = ImageUtil.base64ToImage(img);
                inputStream = new ByteArrayInputStream(imageBytes);
            }
            openCarDataService.recordSync(deptId, deviceName, name, licensePlate, time, direction, inputStream);
        }
        //出
        else if (CmdConst.OUT.equals(req.getDirection())) {
            String name = req.getUsername();
            String licensePlate = req.getVLP();
            String deviceName = req.getOutchannelname();
            Date time = DateUtil.parseDate(req.getIntime(), "yyyy-MM-dd HH:mm:ss");
            Integer direction = Direction.OUT.getValue();
            String img = req.getOutpicturedata();

            //base64图片解码
            InputStream inputStream = null;
            if (StringUtils.isNotBlank(img) && img.length() > 1024) {
                byte[] imageBytes = ImageUtil.base64ToImage(img);
                inputStream = new ByteArrayInputStream(imageBytes);
            }
            openCarDataService.recordSync(deptId, deviceName, name, licensePlate, time, direction, inputStream);
        }
        //其他
        else {
            logger.error("进出方向参数错误,{}", req.getDirection());
        }
    }
}
